<template>
	<view class="ln_upload_file">
		<view v-if="config.title" class="uni-file-picker__header">
			<text class="file-title">{{ config.title }}</text>
			<text class="file-count">{{ list.length }}/{{ config.limit }}</text>
		</view>
		<view class="list-item">
			<!-- <view v-if="showFileList"> -->
			<view class="ln-tag" v-for="(item, index) in showList" :key="index">
				<view @click="downFile(item.url)" class="name">{{ item.name }}</view>
				<image v-if="!detail" src="./static/close.png" class="close" @click="deleteFile(index)" />
				<view class="thumbnail-wrapper">
					<image @click="previewImage(item.url)" v-if="item.type === 'image' || item.type === 'png' || item.type === 'jpg' || item.type === 'jpeg' || item.type === 'webp'" class="thumbnail img" :src="item.url" alt="" />
					<image @click="previewPDF(item.url)" v-else-if="item.type === 'application/pdf' || item.type === 'pdf'" src="../../../../static/h5/pdf.png" class="thumbnail" />
					<image @click="previewAudio(item.url)" v-else-if="item.type === 'audio' || item.type === 'amr' || item.type === 'm4a' || item.type === 'wav' || item.type === 'mp3' || item.type === 'flac'" src="../../../../static/h5/audio.png" class="thumbnail" />
					<image @click="previewVideo(item.url)" v-else-if="item.type === 'video' || item.type === 'mp4' || item.type === 'mov'" src="../../../../static/h5/video.png" class="thumbnail" />
					<image v-else src="../../../../static/h5/file.png" class="thumbnail" />
				</view>
				<!-- </view> -->
			</view>
			<view v-if="!detail" @click.stop="changeFile" style="cursor: pointer;flex:50%;">
				<slot>
					<view v-if='showIcon' class="upload_btn">
						<image src="../../../../static/h5/plus.png" />
					</view>
				</slot>
				<view @click.stop="changeFile"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import changeFiles from "./changeFile.js";

	export default {
		props: {
			value: {
				type: Array,
				default: () => [],
			},
			config: {
				type: Object,
				default: () => {
					return {
						size: 20,
						limit: 2,
						title: "",
						headers: {},
						formData: {},
						automatic: false,
						fileMediatype: "all", // 视频 / 图片 / 文件
						mediaTypeFileType: '' // 文件类型中的类型
					};
				},
			},
			action: {
				type: String,
				default: "",
			},
			showFileList: {
				type: Boolean,
				default: true,
			},
			showIcon: {
				type: Boolean,
				default: true
			},
			detail: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				list: []
			};
		},
		computed: {
			showList() {
				if (!this.showFileList) return []
				return this.list
			}
		},
		created() {
			// this.list = this.value
			/* 这里导致第一次会更新到 父组件数据，进行浅克隆可以避免，但是为了不影响到其他人代码，我还是注释了 */
			this.list = JSON.parse(JSON.stringify(this.value)) || []
		},
		watch: {
			value: {
				handler(newV, oldV) {
					let data = [];
					for (let i = 0; i < newV.length; i++) {
						let item = newV[i]
						if (!item.name) {
							console.log(item);
							let name = item.substring(item.lastIndexOf("/") + 1)
							data.push({
								name: name,
								url: item,
								type: name.substring(name.lastIndexOf(".") + 1)
							});
						} else {
							data.push(item);
						}
					}
					this.list = data;
					// console.log('this list', this.list)
				},
				deep: true,
			},
		},
		methods: {
			previewImage(val) {
				let imgArr = []
				imgArr.push(val)
				uni.previewImage({
					urls: imgArr,
					current: imgArr[0]
				})
			},
			// PDF preview
			previewPDF(val) {
				console.log('previewPDF val: ', val)
				let links = encodeURIComponent(val)
				uni.navigateTo({
					url: '/pagesH5/components/showPDF?links=' + links,
				})
			},
			// Video preview
			previewVideo(val) {
				console.log('val: ', val)
				let links = encodeURIComponent(val)
				uni.navigateTo({
					url: '/pagesH5/components/videoPreview?links=' + links,
				})
			},
			// Audio preview
			previewAudio(val) {
				console.log('vaL: ', val)
				let links = encodeURIComponent(val)
				uni.navigateTo({
					url: '/pagesH5/components/audioPreview?links=' + links,
				})
			},
			changeFile() {
				console.log('changeFile');
				let fileType = [];
				if (this.config.fileMediatype === "all") {
					fileType = ["视频", "图片", "文件"];
					uni.showActionSheet({
						itemList: fileType,
						success: (res) => {
							switch (fileType[res.tapIndex]) {
								case "视频":
									this.changeVideo();
									break;
								case "图片":
									this.changeImage();
									break;
								case "文件":
									this.changePaperFile();
									break;
							}
						},
					});
				} else if (this.config.fileMediatype === "video") {
					this.changeVideo();
					return;
				} else if (this.config.fileMediatype === "image") {
					this.changeImage();
					return;
				} else if (this.config.fileMediatype === "file") {
					this.changePaperFile();
					return;
				} else {
					return;
				}
			},
			changeVideo() {
				let _this = this
				console.log('_this.config.mediaTypeFileType: ', _this.config.mediaTypeFileType)
				uni.chooseVideo({
					sourceType: ["camera", "album"],
					success: (res) => {
						if (this.config.automatic)
							this.uploadFile(
								res.tempFilePath,
								res.tempFilePath.substr(res.tempFilePath.lastIndexOf("/") + 1)
							);
						else {
							let name = res.tempFilePath.substr(res.tempFilePath.lastIndexOf("/") + 1)
							console.log('name: ', name)
							let type = name.substring(name.lastIndexOf(".") + 1)
							console.log('type: ', type)
							if (_this.config.mediaTypeFileType !== '' && _this.config.mediaTypeFileType !== 'all') {
								if (_this.config.mediaTypeFileType.split(',').includes(type)) {
									this.pushFileList(
										res.tempFilePath.substr(res.tempFilePath.lastIndexOf("/") + 1),
										res.tempFilePath
									);
								} else {
									uni.showToast({
										title: `上传附件只能是${_this.config.mediaTypeFileType}格式!`,
										icon: 'none'
									});
								}
							} else {
								this.pushFileList(
									res.tempFilePath.substr(res.tempFilePath.lastIndexOf("/") + 1),
									res.tempFilePath
								);
							}
						}
					},
				});
			},
			changeImage() {
				let _this = this
				console.log('_this.config.mediaTypeFileType: ', _this.config.mediaTypeFileType)
				uni.chooseImage({
					count: 9,
					sizeType: ["original", "compressed"],
					sourceType: ["album", "camera"], //从相册选择
					success: (res) => {
						for (let item of res.tempFilePaths) {
							if (this.config.automatic)
								this.uploadFile(item, item.substr(item.lastIndexOf("/") + 1));
							else {
								let name = item.substr(item.lastIndexOf("/") + 1)
								console.log('name: ', name)
								let type = name.substring(name.lastIndexOf(".") + 1)
								console.log('type: ', type)

								if (_this.config.mediaTypeFileType !== '' && _this.config.mediaTypeFileType !== 'all') {
									if (_this.config.mediaTypeFileType.split(',').includes(type)) {
										this.pushFileList(item.substr(item.lastIndexOf("/") + 1), item);
									} else {
										uni.showToast({
											title: `上传附件只能是${_this.config.mediaTypeFileType}格式!`,
											icon: 'none'
										});
									}
								} else {
									this.pushFileList(item.substr(item.lastIndexOf("/") + 1), item);
								}
							}
						}
					},
				});
			},
			changePaperFile() {
				console.log('changePaperFile');
				let _this = this;
				let list = [];
				// #ifdef H5
				console.log('H5: ');
				uni.chooseFile({
					limit: _this.config.limit,
					success: (res) => {
						for (let i = 0, len = res.tempFiles.length; i < len; i++) {
							console.log('tempFiles: ', res.tempFiles[i])

							console.log('size: ', res.tempFiles[i].size)
							if (
								_this.list.length > _this.config.limit ||
								_this.list.length == _this.config.limit
							) {
								uni.showToast({
									title: `您最多选择 ${_this.config.limit} 个文件`,
									icon: "none",
								});
								return;
							} else if (
								res.tempFiles[i].size / 1024 / 1024 >
								_this.config.size
							) {
								uni.showToast({
									title: `选择文件大于${_this.config.size}M`,
									icon: "none",
								});
								// return;
							}
							if (_this.config.automatic) _this.uploadFile(res.tempFilePaths[i], res.tempFiles[i].name);
							else {
								// _this.pushFileList(res.tempFiles[i].name, res.tempFilePaths[i]);
								let name = res.tempFiles[i].name.substr(res.tempFiles[i].name.lastIndexOf("/") + 1)
								console.log('name: ', name)
								let type = name.substring(name.lastIndexOf(".") + 1)
								console.log('type: ', type)
								if (_this.config.mediaTypeFileType !== '' && _this.config.mediaTypeFileType !== 'all') {
									if (_this.config.mediaTypeFileType.split(',').includes(type)) {
										this.pushFileList(res.tempFiles[i].name, res.tempFiles[i].path, res.tempFiles[i]);
									} else {
										uni.showToast({
											title: `上传附件只能是${_this.config.mediaTypeFileType}格式!`,
											icon: 'none'
										});
									}
								} else {
									this.pushFileList(res.tempFiles[i].name, res.tempFiles[i].path, res.tempFiles[i]);
								}
							}
						}
					},
				});
				// #endif

				// #ifdef MP-WEIXIN
				/*console.log('WEIXIN: ');
				wx.chooseMessageFile({
				  limit: _this.config.limit,
				  type: "file",
				  success(res) {
				    for (let i = 0, len = res.tempFiles.length; i < len; i++) {
				      if (
				        _this.list.length > _this.config.limit ||
				        _this.list.length == _this.config.limit
				      ) {
				        uni.showToast({
				          title: `您最多选择 ${_this.config.limit} 个文件`,
				          icon: "none",
				        });
				        return;
				      }
				      else if (res.tempFiles[i].size / 1024 / 1024 > _this.config.size) {
				        uni.showToast({
				          title: `选择文件大于${_this.config.size}M`,
				          icon: "none",
				        });
				        // return;
				      }
				      list.push({
				        name: res.tempFiles[i].name,
				        url: res.tempFiles[i].path,
				        type: res.tempFiles[i].name.substring(res.tempFiles[i].name.lastIndexOf(".") + 1)
				      });
				      if (_this.config.automatic)
				        _this.uploadFile(res.tempFiles[i].path, res.tempFiles[i].name);
				      else
				        _this.pushFileList(res.tempFiles[i].name, res.tempFiles[i].path);
				    }
				  },
				});*/
				// #endif

				// #ifdef APP-PLUS
				changeFiles((res) => {
					console.log('changeFiles', res);
					if (
						_this.list.length > _this.config.limit ||
						_this.list.length == _this.config.limit
					) {
						uni.showToast({
							title: `您最多选择 ${_this.config.limit} 个文件`,
							icon: "none",
						});
						return;
					}

					let obj = res.lastIndexOf("/");
					let name_ = res.substr(obj + 1)
					list.push({
						name: name_,
						url: res,
						type: name_.substring(name_.lastIndexOf(".") + 1)
					});
					if (_this.config.automatic) _this.uploadFile(res, res.substr(obj + 1));
					else {
						let type = name_.substring(name_.lastIndexOf(".") + 1)
						if (_this.config.mediaTypeFileType && _this.config.mediaTypeFileType !== '' && _this.config.mediaTypeFileType !== 'all') {
							if (_this.config.mediaTypeFileType.split(',').includes(type)) {
								_this.pushFileList(res.substr(obj + 1), res);
							} else {
								uni.showToast({
									title: `上传附件只能是${_this.config.mediaTypeFileType}格式!`,
									icon: 'none'
								});
							}
						} else {
							_this.pushFileList(res.substr(obj + 1), res);
						}
					}
				}, "*/*");
				//  #endif
			},
			// 上传文件
			uploadFile(file, name) {
				uni.showLoading({
					mask: true,
					title: "上传中...",
				});
				uni.uploadFile({
					url: this.action,
					filePath: file,
					name: "file",
					formData: this.config.formData,
					header: this.config.headers,
					success: (uploadFileRes) => {
						uploadFileRes = JSON.parse(uploadFileRes.data);
						if (uploadFileRes.code == 200) {
							this.list.push({
								name: name,
								url: uploadFileRes.data,
								type: name.substring(name.lastIndexOf(".") + 1)
							});
							this.$emit("input", this.list);
							this.$emit("change-file", this.list);
						}
					},
					complete: () => {
						uni.hideLoading();
					},
				});
			},
			deleteFile(index) {
				let fileList = this.list
				fileList.splice(index, 1);
				this.list = fileList
				this.$emit("input", this.list);
				this.$emit("change-file", fileList, index);
				this.$emit("on-remove", fileList, index);
			},
			pushFileList(name, url, file = '') {
				const item = {
					name: name,
					url: url,
					type: name.substring(name.lastIndexOf(".") + 1),
					file: file
				}
				this.list.push(item);
				this.$emit("change-file", this.list);
				this.$emit("on-upload", item);
			},
			downFile(url) {
				this.$emit("change-list", url);
			},
		},
	};
</script>

<style scoped lang="scss">
	.ln_upload_file {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.uni-file-picker__header {
		padding-top: 5px;
		padding-bottom: 10px;
		display: flex;
		justify-content: space-between;
	}

	.file-title {
		font-size: 14px;
		color: #333;
	}

	.file-count {
		font-size: 14px;
		color: #999;
	}

	.list-item {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		gap: 20rpx;
		//justify-content: space-between;


		.ln-tag {
			max-width: 286rpx;
			height: 286rpx;
			flex: 0 0 calc(50% - 20rpx);
			position: relative;
			// max-width: 2500rpx;
			// display: flex;
			// flex-wrap: wrap;
			// justify-content: space-between;
			background-color: rgba(85, 170, 255, 0.2);
			padding: 8rpx 25rpx;
			border-radius: 8rpx;
			font-size: 28rpx;
			color: rgba(85, 170, 255, 1);
			border: 1rpx solid rgba(85, 170, 255, 0.8);
			margin: 0 10rpx 10rpx;
			align-items: center;
			cursor: pointer;

			.name {
				word-break: break-all;
				white-space: pre-wrap;
				word-break: break-all;
				// text-overflow: ellipsis;
				// display: -webkit-box;
				// -webkit-box-orient: vertical;
				// -webkit-line-clamp: 2;

				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;

				overflow: hidden;
			}

			.close {
				width: 30rpx;
				height: 30rpx;
				margin: 0 0 0 10rpx;
				position: absolute;
				right: 15rpx;
				bottom: 10px;
			}
		}

		.thumbnail-wrapper {
			display: flex;
			justify-content: center;
			align-items: center;

			.thumbnail {
				max-width: 80px;
				max-height: 80px;
				width: 50px;
				height: 60px;
				margin-top: 15px;

				&.img {
					max-width: 240rpx;
					max-height: 280rpx;
					width: 100%;
					height: 180rpx;
				}
			}
		}
	}

	.upload_btn {
		background-color: #fbfdff;
		border: 1px dashed #c0ccda;
		border-radius: 6px;
		box-sizing: border-box;
		max-width: 286rpx;
		height: 286rpx;
		flex: 0 0 calc(50% - 20rpx);
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 0 5px;

		image {
			width: 80rpx;
			height: 80rpx;
		}
	}
</style>